<?
require_once('unicode.php');

function print_entry($key,$entry,$start,$end = false)
{
  if($start >= count($entry)) return;

  $line = sprintf("'%s': [",$key);
  for($i=$start;$i<count($entry);$i++) {
    $value = $entry[$i];
    if($value >= 0xd800 && $value <= 0xdfff) die("Error\n");
    if($value > 0x10ffff) die("Error\n");
    $line .= sprintf("0x%x,",$value);

    if($end !== false && $i >= $end) break;
  }
  $line = rtrim($line,',');
  $line .= "],";
  printf("%s\n",$line);
}


if(count($argv) < 2) return;

$fp = fopen($argv[1],'r');

$entries = array();
while($line = fgets($fp)) {
  $line = rtrim($line,"\n");
  $pos = strpos($line,' ');
  $txt = substr($line,0,$pos);
  $data = substr($line,$pos+1);
  $scalar = readutf8($data);

  if(key_exists($txt,$entries)) {
    $entry = $entries[$txt];
    $entry[] = $scalar;
    $entries[$txt] = $entry;
  }
  else {
    $entry = array();
    $entry[] = $scalar;
    $entries[$txt] = $entry;
  }
}
fclose($fp);

printf("table: {\n");
foreach($entries as $key => $entry) {
  print_entry($key,$entry,0,16); // 1-2 pages
}
printf("},\n");

printf("//BEGIN_COMPONENT{table0}\n");
printf("table0: {\n");
foreach($entries as $key => $entry) {
  print_entry($key,$entry,17,34); // 3-4 pages
}
printf("},\n");
printf("//END_COMPONENT\n");

printf("//BEGIN_COMPONENT{table1}\n");
printf("table1: {\n");
foreach($entries as $key => $entry) {
  print_entry($key,$entry,35); // rest of all
}
printf("},\n");
printf("//END_COMPONENT\n");

?>
